{% extends "base.html" %}

{% block title %}参数配置管理 - 告警系统{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1"><i class="bi bi-sliders me-2"></i>参数配置管理</h2>
            <p class="text-muted mb-0">管理系统参数配置信息</p>
        </div>
        <div class="d-flex align-items-center gap-3">
            <!-- MQTT状态指示器 -->
            <div class="d-flex align-items-center">
                <span class="me-2">MQTT:</span>
                {% if mqtt_connected %}
                <span class="badge bg-success rounded-pill">
                    <i class="bi bi-plug me-1"></i> 已连接
                </span>
                {% else %}
                <span class="badge bg-danger rounded-pill">
                    <i class="bi bi-plug-fill me-1"></i> 未连接
                </span>
                {% endif %}
            </div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addParameterModal">
                <i class="bi bi-plus-circle me-1"></i> 添加新参数
            </button>
        </div>
    </div>

    <!-- MQTT操作状态提示 -->
    {% if error %}
    <div class="alert alert-danger alert-dismissible fade show mb-4">
        <i class="bi bi-exclamation-circle me-2"></i> {{ error }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    {% endif %}
    
    {% if success %}
    <div class="alert alert-success alert-dismissible fade show mb-4">
        <i class="bi bi-check-circle me-2"></i> {{ success }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    {% endif %}
    
    <!-- 搜索和过滤 -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form class="row g-3">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control" placeholder="搜索参数名称、设备参数或描述..." 
                               name="search" value="{{ search or '' }}">
                    </div>
                </div>
                <div class="col-md-4">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-search me-1"></i> 搜索
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 参数配置表格 -->
    <div class="card shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>序号</th>
                            <th>系统参数名称</th>
                            <th>设备参数名称</th>
                            <th>参数值</th>
                            <th>参数描述</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% if Parameters|length == 0 %}
                        <tr>
                            <td colspan="7" class="text-center py-5">
                                <div class="py-4">
                                    <i class="bi bi-database-exclamation fs-1 text-muted"></i>
                                    <h5 class="mt-3">未找到参数配置</h5>
                                    <p class="text-muted">请添加新参数或修改搜索条件</p>
                                </div>
                            </td>
                        </tr>
                        {% else %}
                            {% for param in Parameters %}
                            <tr>
                                <td class="fw-bold">{{ param.display_id }}</td>
                                <td>{{ param.ParameterName }}</td>
                                <td>{{ param.DeviceParameter or '-' }}</td>
                                <td>
                                    <span class="badge bg-primary-subtle text-primary">
                                        {{ param.ParameterValue }}
                                    </span>
                                </td>
                                <td>
                                    <div class="text-truncate" style="max-width: 250px;" 
                                         title="{{ param.ParameterDescription }}">
                                        {{ param.ParameterDescription or '-' }}
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex gap-2">
                                        <a href="/editparameter/{{ param.ParameterId }}" 
                                           class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-pencil"></i> 编辑
                                        </a>
                                        <!-- 仅当设备参数名称存在时才显示同步按钮 -->
                                        {% if param.DeviceParameter %}
                                        <button class="btn btn-sm btn-outline-success send-mqtt-btn" 
                                                data-id="{{ param.ParameterId }}"
                                                data-name="{{ param.ParameterName }}"
                                                data-value="{{ param.ParameterValue }}">
                                            <i class="bi bi-send"></i> 同步所有设备
                                        </button>
                                        {% endif %}
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        {% endif %}
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            {% if total_pages > 1 %}
            <nav class="px-3 py-3">
                <ul class="pagination justify-content-end mb-0">
                    {% if current_page > 1 %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ current_page-1 }}&search={{ search or '' }}">
                            <i class="bi bi-chevron-left"></i>
                        </a>
                    </li>
                    {% endif %}
                    
                    {% for p in range(1, total_pages+1) %}
                    <li class="page-item {% if p == current_page %}active{% endif %}">
                        <a class="page-link" href="?page={{ p }}&search={{ search or '' }}">{{ p }}</a>
                    </li>
                    {% endfor %}
                    
                    {% if current_page < total_pages %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ current_page+1 }}&search={{ search or '' }}">
                            <i class="bi bi-chevron-right"></i>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

<!-- 添加参数模态框 -->
<div class="modal fade" id="addParameterModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>添加新参数</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="/add_parameter">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">参数名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="ParameterName" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">设备参数名称</label>
                        <input type="text" class="form-control" name="DeviceParameter">
                        <small class="text-muted">设备端使用的参数名称，如果为空则使用参数名称</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">参数值 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="ParameterValue" required>
                    </div>
                    
                    <!-- <div class="mb-3">
                        <label class="form-label">设备IP <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="BoardIp" required>
                        <small class="text-muted">设备的IP地址，系统会自动查找对应设备ID</small>
                    </div> -->
                    
                    <div class="mb-3">
                        <label class="form-label">参数描述</label>
                        <textarea class="form-control" name="ParameterDescription" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">添加参数</button>
                </div>
            </form>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 显示操作消息提示
    const urlParams = new URLSearchParams(window.location.search);
    if(urlParams.has('success') || urlParams.has('error')) {
        setTimeout(function() {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }, 100);
    }
    
    // 添加参数模态框显示时清除表单
    const addModal = document.getElementById('addParameterModal');
    if(addModal) {
        addModal.addEventListener('show.bs.modal', function () {
            const form = this.querySelector('form');
            if(form) form.reset();
        });
    }
    
    // 处理发送到MQTT按钮
    document.querySelectorAll('.send-mqtt-btn').forEach(button => {
        button.addEventListener('click', function() {
            const paramId = this.getAttribute('data-id');
            const paramName = this.getAttribute('data-name');
            const paramValue = this.getAttribute('data-value');
            
            // 更新按钮状态
            const originalHTML = this.innerHTML;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 发送中...';
            this.disabled = true;
            
            // 发送AJAX请求
            fetch(`/send_parameter/${paramId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    // 显示成功提示
                    showToast('success', `参数 "${paramName}=${paramValue}" 已发送到设备`);
                } else {
                    // 显示错误提示
                    showToast('danger', `发送失败: ${data.message || '未知错误'}`);
                }
            })
            .catch(error => {
                showToast('danger', `请求失败: ${error.message}`);
            })
            .finally(() => {
                // 恢复按钮状态
                this.innerHTML = originalHTML;
                this.disabled = false;
            });
        });
    });
    
    // 显示Toast通知
    function showToast(type, message) {
        // 创建Toast元素
        const toastEl = document.createElement('div');
        toastEl.className = `toast align-items-center text-white bg-${type} border-0`;
        toastEl.setAttribute('role', 'alert');
        toastEl.setAttribute('aria-live', 'assertive');
        toastEl.setAttribute('aria-atomic', 'true');
        
        toastEl.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                <i class="bi ${type === 'success' ? 'bi-check-circle' : 'bi-exclamation-circle'} me-2"></i>
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
        
        // 添加到容器
        const toastContainer = document.getElementById('toastContainer');
        if (!toastContainer) {
            // 创建容器如果不存在
            const container = document.createElement('div');
            container.id = 'toastContainer';
            container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            container.style.zIndex = '9999';
            document.body.appendChild(container);
        }
        
        document.getElementById('toastContainer').appendChild(toastEl);
        
        // 初始化并显示Toast
        const toast = new bootstrap.Toast(toastEl, {
            autohide: true,
            delay: 3000
        });
        toast.show();
    }
});
</script>
{% endblock %}